import type { Router, RouteRecordNormalized, RouteRecordRaw } from 'vue-router';
import NProgress from 'nprogress'; // progress bar

import usePermission from '@/hooks/permission';
import { useUserStore, useAppStore } from '@/store';
import { appRoutes } from '../routes';
import { WHITE_LIST, NOT_FOUND } from '../constants';

// 修正常量定义，确保与路由名称一致
const NOT_FOUND_NAME = 'notFound';

export default function setupPermissionGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    const appStore = useAppStore();
    const userStore = useUserStore();
    const Permission = usePermission();
    const permissionsAllow = Permission.accessRouter(to);
    
    // 增强刷新检测逻辑
    const pathname = window.location.pathname;
    const search = window.location.search;
    const hash = window.location.hash;
    
    // 检测是否为刷新操作的多种方法
    const isRefreshByPath = to.fullPath === pathname + search;
    const isRefreshByHash = hash.includes(to.path);
    const isFromEmpty = from.name === undefined && from.path === '/';
    const isRefreshing = isRefreshByPath || isRefreshByHash || isFromEmpty;
    
    console.log('路由守卫检查:', {
      目标路由: to.path,
      来源路由: from.path,
      目标fullPath: to.fullPath,
      menuFromServer: appStore.menuFromServer,
      已有菜单数量: appStore.appAsyncMenus.length,
      用户角色: userStore.role,
      权限允许: permissionsAllow,
      当前URL: window.location.href,
      当前pathname: pathname,
      当前search: search,
      当前hash: hash,
      isRefreshByPath: isRefreshByPath,
      isRefreshByHash: isRefreshByHash,
      isFromEmpty: isFromEmpty,
      最终刷新状态: isRefreshing,
      WHITE_LIST: WHITE_LIST,
      to_name: to.name,
      is_in_whitelist: WHITE_LIST.includes(to.name as string),
      is_notfound: to.name === NOT_FOUND_NAME
    });
    
    // 白名单路由直接通过 (修正白名单检查)
    if (WHITE_LIST.includes(to.name as string) || to.name === NOT_FOUND_NAME) {
      console.log('【返回点1】白名单路由，直接通过:', to.path, '路由名称:', to.name);
      // 即使是白名单路由，也记录刷新状态
      if (isRefreshing) {
        console.log('检测到白名单路由的页面刷新操作:', {
          当前URL: window.location.href,
          目标路由: to.fullPath,
          路由名称: to.name
        });
      }
      next();
      NProgress.done();
      return;
    }
    
    // 如果已经是 not-found 页面，直接通过，避免重定向循环
    if (to.name === NOT_FOUND_NAME) {
      console.log('【返回点2】已经是404页面，直接通过:', to.path);
      next();
      NProgress.done();
      return;
    }
    
    // 确保用户已登录，如果用户信息不存在，先尝试恢复用户信息
    if (!userStore.role) {
      try {
        console.log('用户信息未加载，尝试恢复...');
        await userStore.info();
        console.log('用户信息恢复成功:', userStore.role);
      } catch (error) {
        console.error('【返回点3】恢复用户信息失败:', error);
        // 如果恢复失败，可能是未登录状态，重定向到登录页
        next('/login');
        NProgress.done();
        return;
      }
    }
    
    if (appStore.menuFromServer) {
      // 针对来自服务端的菜单配置进行处理
      // Handle routing configuration from the server
      console.log('使用服务器菜单配置');

      // 根据需要自行完善来源于服务端的菜单配置的permission逻辑
      // Refine the permission logic from the server's menu configuration as needed
      if (!appStore.appAsyncMenus.length) {
        console.log('没有服务器菜单数据，尝试获取...');
        try {
          await appStore.fetchServerMenuConfig();
          console.log('获取服务器菜单完成，菜单数量:', appStore.appAsyncMenus.length);
        } catch (error) {
          console.error('获取服务器菜单失败:', error);
        }
      }
      
      // 如果没有获取到菜单数据，尝试使用默认路由
      if (!appStore.appAsyncMenus.length) {
        console.warn('【返回点4】未能获取到菜单数据，尝试使用默认路由');
        if (permissionsAllow) {
          next();
        } else {
          next('/dashboard/workplace');
        }
        NProgress.done();
        return;
      }
      
      const serverMenuConfig = [...appStore.appAsyncMenus, ...WHITE_LIST.map(name => ({ name }))];
      console.log('检查路由是否存在于菜单中:', to.name);
      console.log('可用的菜单路由:', serverMenuConfig.map(item => item.name));
      console.log('当前路由信息:', {
        name: to.name,
        path: to.path,
        fullPath: to.fullPath,
        params: to.params,
        query: to.query,
        meta: to.meta
      });

      let exist = false;
      let matchedRoute = null;
      
      // 先检查路由名称是否匹配
      const routesByName = router.getRoutes().filter(r => r.name === to.name);
      if (routesByName.length > 0) {
        exist = true;
        matchedRoute = routesByName[0];
        console.log('通过名称找到匹配的路由:', matchedRoute);
      } 
      // 再检查路径是否匹配
      else {
        const matchedRoutes = router.getRoutes().filter(r => {
          // 精确匹配路径
          if (r.path === to.path) return true;
          
          // 检查是否是带参数的路径
          const pathRegex = new RegExp(
            `^${r.path.replace(/:[^/]+/g, '[^/]+')}$`
          );
          return pathRegex.test(to.path);
        });
        
        if (matchedRoutes.length > 0) {
          exist = true;
          matchedRoute = matchedRoutes[0];
          console.log('通过路径找到匹配的路由:', matchedRoute);
        }
      }
      
      // 如果上面的方法都没找到，再尝试在菜单配置中查找 (修复：不修改原数组)
      if (!exist) {
        // 创建菜单拷贝，避免修改原数组
        const menuConfigCopy = [...serverMenuConfig];
        
        // 定义更通用的菜单项类型以适配白名单项
        type MenuItem = RouteRecordNormalized | { name: string; path?: string; children?: MenuItem[] };
        
        const checkRouteInMenu = (menuItems: MenuItem[]) => {
          for (const item of menuItems) {
            if (item.name === to.name || (item.path && item.path === to.path)) {
              exist = true;
              matchedRoute = item;
              console.log('在菜单中找到匹配的路由:', item);
              return true;
            }
            
            // 修复类型错误：确保children是MenuItem[]类型
            if (item.children && item.children.length) {
              const children = item.children as MenuItem[];
              if (checkRouteInMenu(children)) {
                return true;
              }
            }
          }
          return false;
        };
        
        checkRouteInMenu(menuConfigCopy);
      }
      
      if (isRefreshing) {
        console.log('检测到页面刷新操作:', {
          当前URL: window.location.href,
          目标路由: to.fullPath,
          pathname: window.location.pathname,
          search: window.location.search,
          hash: window.location.hash,
          检测方法: {
            isRefreshByPath,
            isRefreshByHash,
            isFromEmpty
          }
        });
      }
      
      // 增加判断顺序，确保刷新优先级高于存在性判断
      if (isRefreshing) {
        console.log('刷新操作，直接允许访问:', to.path);
        next();
      } 
      else if (exist && permissionsAllow) {
        console.log('路由存在且有权限，允许访问:', to.path);
        next();
      } else {
        console.warn('路由不存在或无权限，重定向到404:', to.path);
        // 修正重定向到404的方式
        next({ name: NOT_FOUND_NAME });
      }
    } else {
      // eslint-disable-next-line no-lonely-if
      // 本地菜单模式也要优先处理刷新
      if (isRefreshing) {
        console.log('本地菜单模式，检测到刷新，直接允许访问:', to.path);
        next();
      }
      else if (permissionsAllow) {
        console.log('本地菜单模式，有权限，允许访问:', to.path);
        next();
      } else {
        console.warn('本地菜单模式，无权限，寻找第一个有权限的路由');
        const destination =
          Permission.findFirstPermissionRoute(appRoutes, userStore.role) ||
          NOT_FOUND_NAME;
        console.log('重定向到:', destination);
        next(destination);
      }
    }
    NProgress.done();
  });
}
